package com.example.administrator.myjdlc.Thread;

import android.annotation.SuppressLint;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/***
 * 线程池管理
 * @author shengzg
 *
 */
public class CustomThreadPoolExecutor {    
    
    
		private ThreadPoolExecutor pool = null;    
		    
		    
		/**
		 *  核心线程池大小
		 */
		private static final int corePoolSize = 2;
		
		/**
		 * maximumPoolSize
		 */
		private static final int maximumPoolSize = 5;
		
		/**
		 * keepAliveTime 线程池中超过corePoolSize数目的空闲线程最大存活时间----30+单位TimeUnit
		 */
	    private static final int keepAliveTime = 30;
		
		
		/**  
		 * 线程池初始化方法  
		 *   
		 * corePoolSize 核心线程池大小----1  
		 * maximumPoolSize 最大线程池大小----3  
		 * keepAliveTime 线程池中超过corePoolSize数目的空闲线程最大存活时间----30+单位TimeUnit  
		 * TimeUnit keepAliveTime时间单位----TimeUnit.MINUTES  
		 * workQueue 阻塞队列----new ArrayBlockingQueue<Runnable>(5)====5容量的阻塞队列  
		 * threadFactory 新建线程工厂----new CustomThreadFactory()====定制的线程工厂  
		 * rejectedExecutionHandler 当提交任务数超过maxmumPoolSize+workQueue之和时,  
		 *                          即当提交第41个任务时(前面线程都没有执行完,此测试方法中用sleep(100)),  
		 *                                任务会交给RejectedExecutionHandler来处理  
		 */    
		@SuppressLint("NewApi") public void init() {    
		    pool = new ThreadPoolExecutor(    
		    		corePoolSize,    
		    		maximumPoolSize,    
		    		keepAliveTime,    
		            TimeUnit.MINUTES,    
		            new ArrayBlockingQueue<Runnable>(5),    
		            new CustomThreadFactory(),    
		            new CustomRejectedExecutionHandler());    
		}    

	    
	public void destory() {    
	    if(pool != null) {    
	        pool.shutdownNow();    
	    }    
	}    
	    
	    
	public ExecutorService getCustomThreadPoolExecutor() {    
	    return this.pool;    
	}    
    
	private class CustomThreadFactory implements ThreadFactory {    
	
	    private AtomicInteger count = new AtomicInteger(0);    
	        
	    @Override    
	    public Thread newThread(Runnable r) {    
	        Thread t = new Thread(r);    
	        String threadName = CustomThreadPoolExecutor.class.getSimpleName() + count.addAndGet(1);    
	        System.out.println(threadName);    
	        t.setName(threadName);    
	        return t;    
	    }    
	}    
    
    
	private class CustomRejectedExecutionHandler implements RejectedExecutionHandler {    
	
	    @Override    
	    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {    
	        try {  
	            // 核心改造点，由blockingqueue的offer改成put阻塞方法  
	            executor.getQueue().put(r);  
	        } catch (InterruptedException e) {  
	            e.printStackTrace();  
	        }  
	    }    
	}    


	/*public void execute(Runnable command) {  
	    if (command == null)  
	        throw new NullPointerException();  
	
	    int c = ctl.get();  
	    if (workerCountOf(c) < corePoolSize) {  
	        if (addWorker(command, true))  
	            return;  
	        c = ctl.get();  
	    }  
	    if (isRunning(c) && workQueue.offer(command)) {  
	        int recheck = ctl.get();  
	        if (! isRunning(recheck) && remove(command))  
	            reject(command);  
	        else if (workerCountOf(recheck) == 0)  
	            addWorker(null, false);  
	    }  
	    else if (!addWorker(command, false))  
	        // 进入拒绝机制， 我们把runnable任务拿出来，重新用阻塞操作put，来实现提交阻塞功能  
	        reject(command);  
	} */
   
}     